<script setup lang="ts">
const { startCount = 100, lineDistance = 80 } = defineProps<{
  startCount: number;
  lineDistance: number;
}>();
const canvas = useTemplateRef("canvas");
const stars: Star[] = [];
onMounted(() => {
  canvas.value!.width = window.innerWidth;
  canvas.value!.height = window.innerHeight;
  const ctx = canvas.value!.getContext("2d") as CanvasRenderingContext2D;
  for (let i = 0; i < startCount; i++) {
    const x = Math.random() * canvas.value!.width;
    const y = Math.random() * canvas.value!.height;
    const r = Math.random() * 3 + 1;
    const speedX = Math.random() * 2 - 1;
    const speedY = Math.random() * 2 - 1;
    stars.push(new Star({ x, y, r, speedX, speedY }));
    stars[i].draw(ctx);
  }
  setInterval(() => {
    ctx.clearRect(0, 0, canvas.value!.width, canvas.value!.height);
    stars.forEach((star) => {
      star.draw(ctx);
      star.move(ctx);
      stars.forEach((star2) => {
        star2!.link(ctx, star);
      });
    });
  });
});

interface IStarProps {
  x: number;
  y: number;
  r: number;
  speedX: number;
  speedY: number;
}
class Star {
  x: number;
  y: number;
  r: number;
  speedX: number;
  speedY: number;
  // draw: (ctx: CanvasRenderingContext2D) => void
  constructor({ x, y, r, speedX, speedY }: IStarProps) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.speedX = speedX;
    this.speedY = speedY;
  }

  draw(ctx: CanvasRenderingContext2D) {
    ctx.fillStyle = "#fff";
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
    ctx.fill();
    ctx.closePath();
  }

  move(ctx: CanvasRenderingContext2D) {
    this.x += this.speedX;
    this.y += this.speedY;
    if (this.x < 0 || this.x > ctx.canvas.width) {
      this.speedX = -this.speedX;
    }
    if (this.y < 0 || this.y > ctx.canvas.height) {
      this.speedY = -this.speedY;
    }
    this.draw(ctx);
  }

  link(ctx: CanvasRenderingContext2D, star: Star) {
    const dx = this.x - star.x;
    const dy = this.y - star.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    if (distance < lineDistance) {
      ctx.beginPath();
      ctx.moveTo(this.x, this.y);
      ctx.lineTo(star.x, star.y);
      ctx.closePath();
      ctx.strokeStyle = "#fff";
      ctx.stroke();
    }
  }
}
</script>

<template>
  <div>
    <canvas ref="canvas" />
  </div>
</template>
